<?php
/**
 * Date: 2024-07-06
 */

namespace module\ai\controller\admin;

use app\library\Controller;
use module\ai\front\form\ChannelForm;
use module\ai\library\channel\Factory;
use module\ai\logic\ChannelLogic;
use mof\annotation\AdminPerm;
use mof\annotation\Inject;
use mof\ApiResponse;
use think\response\Json;

#[AdminPerm(
    title: 'AI通道', url: 'ai/channel', actions: '*,!flags',
    sort: 2, icon: 'Guide', group: 'main'
)]
class Channel extends Controller
{
    #[Inject]
    protected ChannelLogic $logic;

    #[Inject]
    protected ChannelForm $form;

    public function platform(): Json
    {
        return ApiResponse::success(
            Factory::platformDict()->toElementData()->toSelectOptions()
        );
    }

    public function index(): Json
    {
        return ApiResponse::success(
            $this->logic->paginate($this->request->searcher())
        );
    }

    public function create($flag): Json
    {
        $form = $this->form->build(
            $this->logic->model()->newInstance(['flag' => $flag])
        );
        return ApiResponse::success($form);
    }

    public function edit($id): Json
    {
        $form = $this->form->build($this->logic->read($id));
        return ApiResponse::success($form);
    }

    public function save(): Json
    {
        return ApiResponse::success($this->logic->save($this->form->get()));
    }

    public function update($id): Json
    {
        $data = $this->form->withScene('edit')->withFixed(['id' => $id])->get();
        return ApiResponse::success($this->logic->update($id, $data));
    }

    public function delete($id): Json
    {
        $this->logic->delete($id);
        return ApiResponse::success();
    }
}